<?php

namespace Shared\Doctrine\Mysql\StringFunction;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;

/**
 * CaseWhenFunction ::=  "CASEWHEN" "(" ConditionalExpression ")" "then" StringPrimary "else" StringPrimary "end" 
 *
 */
class Casewhen extends FunctionNode {

	public $cases = array();
	public $else;

	public function getSql(SqlWalker $sqlWalker) {
		$buildSQL = 'CASE';
		foreach ($this->cases as $case) {
			$buildSQL .= ' WHEN ' . $sqlWalker->walkSimpleArithmeticExpression($case['when']) . ' THEN ' . $sqlWalker->walkArithmeticExpression($case['then']);
		}
		$buildSQL .= ' ELSE ' . $sqlWalker->walkStringPrimary($this->else) . ' END';
		return $buildSQL;
	}

	public function parse(Parser $parser) {
		while ($parser->getLexer()->isNextToken(Lexer::T_COMMA) || !$this->cases) {
			$parser->match(Lexer::T_IDENTIFIER);
			if ($this->cases) {
				$parser->match(Lexer::T_COMMA);
			}
			$conditionExpr = $parser->ConditionalExpression();
			$parser->match(Lexer::T_IDENTIFIER);
			$thenExpr = $parser->ArithmeticExpression();

			$this->cases[] = array(
				'when' => $conditionExpr,
				'then' => $thenExpr
			);
		}
		$parser->match(Lexer::T_IDENTIFIER);
		$this->else = $parser->ArithmeticExpression();
		$parser->match(Lexer::T_IDENTIFIER);
	}

}

